<?php

declare(strict_types=1);

namespace App\Request\Admin;

use App\Request\FormRequest;
use Hyperf\Validation\Rule;

class Menu extends FormRequest
{
    /**
     * 验证场景
     * @var array|\string[][]
     */
    protected array $scenes = [
        'save' => [
            'parent_id',
            'name',
            'icon',
            'path',
            'status',
            'desc',
            'app'
        ],
        'update' => [
            'parent_id',
            'name',
            'icon',
            'path',
            'status',
            'desc',
            'app'
        ],
        'sort' => [
            'id'
        ],
        'destroy' => [
            'ids',
            'ids.*'
        ],
        'index' => [
            'app'
        ]
    ];

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $rules = [
            'parent_id' => 'numeric|min:0',
            'name' => [
                'required',
                'max:8',
                Rule::unique('menu')->where(function ($query){
                    $query->where('parent_id', $this->input('parent_id', 0))
                        ->where('app', $this->input('app', getApp()));
                })->ignore($this->route('id'))
            ],
            'icon' => 'nullable|icon',
            'path' => 'nullable|path',
            'desc' => 'max:80',
            'id' => 'required|numeric|min:1',
            'app' => 'nullable|app',
            'ids' => 'required|array',
            'ids.*' => 'required|numeric|min:1'
        ];

        if (getAction() === 'index') {
            $rules['app'] = 'required|app';
        }

        return $rules;
    }
}
